#!/bin/bash

source /etc/profile
#export JAVA_HOME=/opt/jdk1.7.0_80
#export JRE_HOME=/opt/jdk1.7.0_80/jre
#export PATH=$JAVA_HOME/bin:$PATH
#export CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
#export LC_ALL=zh_CN.UTF-8

#function usage means how to use this script.
usage()
{
    echo "Usage: $0 -s [stop|start|restart|status] -p port"
}

#if no parameter is passed to script then show how to use.
if [ $# -eq 0 ]
then
    usage
    exit
fi

#get args parameters in $s and $port
while getopts ":s:p:" opt
do
    case $opt in 
        s)
        s=$OPTARG
        if [ "$s" != "start" -a "$s" != "stop" -a "$s" != "restart" -a "$s" != "status" ];then 
        echo "-s error:$s"
        usage
        exit 1
        fi;;    
        p)
        port=$OPTARG
        if [ $port -gt 65535 ];then    
        echo "-p error"
        usage
        exit 1
        fi;;
    esac 
done

#gets pid of specific port
pid=`netstat -lpn |grep :::$port|awk '{print $7}'|awk -F / '{print $1}'`
binPath=`find /home/ACS/ -type d -name 'bin'|grep $port`

# Function to kill Java processes related to the port
kill_old_java_processes() {
    echo "检查并杀掉多余的 Java 进程..."
    # 获取所有运行 Java 程序的 PID，检查是否与当前端口相关
    pids=$(ps aux | grep java | grep -i "$port" | awk '{print $2}')
    if [ ! -z "$pids" ]; then
        echo "终止以下 Java 进程：$pids"
        kill -9 $pids
    fi
}

if [ $s == "restart" ];then
    # Kill old Java processes before restarting
    kill_old_java_processes
    
    # Handle the process if no PID found
    if [ ! $pid ];then
        echo -e "ACS 已停止，正在启动 ACS $port <br \>"
        echo $binPath
        cd $binPath
        nohup sh startup.sh &
        exit 0
    fi
    
    echo "杀掉 ACS 进程 $port <br \>"
    kill -9 $pid
    echo "重新启动 ACS $port <br \>"
    cd $binPath
    nohup sh startup.sh &

elif [ $s == "start" ];then
    # Kill old Java processes before starting new one
    kill_old_java_processes
    
    echo "启动 ACS $port"
    echo $binPath
    cd $binPath
    nohup sh startup.sh & 

elif [ $s == "stop" ];then
    echo "停止 ACS $port"
    kill -9 $pid

elif [ $s == "status" ];then
    # Show the status of ACS for a specific port
    netstat -ntlp | grep $port
fi